﻿using Microsoft.Extensions.Hosting;
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Threading;
using System.Threading.Tasks;

namespace PluginSample
{
    public class SimpleService
    {
        public CancellationTokenSource CancellationTokenSource;
        public SimpleService()
        {
            CancellationTokenSource = new CancellationTokenSource();
        }
        public void Run(string name)
        {
            Console.WriteLine($"Hello {name}!");
        }

        public Task RunAsync(string name)
        {
            Console.WriteLine($"Hello {name}!");
            return Task.CompletedTask;
        }
        public Task RunTask(string name)
        {
            return Task.Run(() => {
                Console.WriteLine($"Hello {name}!");
            });
        }
        public Task RunWaitTask(string name)
        {
            return Task.Run( async ()=> {
                while (true)
                {
                    if (CancellationTokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                    await Task.Delay(1000);
                    Console.WriteLine($"Hello {name}!");
                }
            });
        }
        public Task RunWaitTaskForCancel(string name, CancellationToken cancellation)
        {
            return Task.Run(async () => {
                while (true)
                {
                    if (cancellation.IsCancellationRequested)
                    {
                        break;
                    }
                    await Task.Delay(1000);
                    Console.WriteLine($"Hello {name}!");
                }
            });
        }
        public async Task RunWait(string name)
        {
            while (true)
            {
                if (CancellationTokenSource.IsCancellationRequested)
                {
                    break;
                }
                await Task.Delay(1000);
                Console.WriteLine($"Hello {name}!");
            }

        }
        public Task RunWaitNewTask(string name)
        {
            return Task.Factory.StartNew(async ()=> {
                while (true)
                {
                    if (CancellationTokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                    await Task.Delay(1000);
                    Console.WriteLine($"Hello {name}!");
                }
            },TaskCreationOptions.DenyChildAttach);
        }
        public void Cancel()
        {
            CancellationTokenSource.Cancel();
            CancellationTokenSource.Dispose();
        }
    }
}
